package com.jiang.entity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Socket;

/**
 * 对等线程
 * 将reader和writer两个分开，是为了读写分开，使得单向数据不会阻塞
 */
public class PeerThread extends Thread{
    private static final Logger LOGGER = LoggerFactory.getLogger(PeerThread.class);
    public Socket socket;
    public PeerReader peerReader;
    public PeerWriter peerWriter;

    /**
     * 传入套接字
     * @param socket
     */
    public PeerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //对等线程接收的就是每个访问对等网络监听端口的套接字
        LOGGER.info("Got connection from "+socket.getInetAddress()+".");
        peerReader = new PeerReader(socket);
        peerReader.start();
        peerWriter = new PeerWriter(socket);
        peerWriter.start();
    }

    /**
     * 发送数据
     * @param data
     */
    public void send(String data){
        if(peerWriter == null){
            LOGGER.error("Couldn't send "+data+" when outputThread is null");
        }else {
            peerWriter.write(data);//写入缓冲区
            LOGGER.info("Write success");
        }
    }
}
